package com.hou.shopping.product.exception;


import com.hou.shopping.common.exception.BizCodeEnume;
import com.hou.shopping.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
//@ResponseBody//数据要写回去，由于所有的方法，所以就放在类上
//@ControllerAdvice(basePackages = "com.hou.shopping.product.controller")
@RestControllerAdvice(basePackages = "com.hou.shopping.product.controller")//上边两个的结合
public class ShoppingExceptionControllerAvice {
    @ExceptionHandler(value = Exception.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现的问题{}，异常类型{}", e.getMessage(), e.getClass());
        Map<String, String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((item) -> {
//                获取的错误提示
            String defaultMessage = item.getDefaultMessage();
            String field = item.getField();//出错的名称
            map.put(field, defaultMessage);
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
